/**
 * 
 */
package string.passed;

/**
 * @author xyyi
 *
 */
public class LongestCommonPrefix {
	/**
	 Write a function to find the longest common prefix string amongst an array of strings.
	 */
	public String longestCommonPrefix(String[] strs) {
		if (strs == null || strs.length == 0)
			return null;
		if (strs.length == 1)
			return strs[0];
		int scanIndex = 0; // scan index to indicate the current scan position of all strings 
		while (true) {
			for (int i = 0; i < strs.length - 1; i++) {
				if (strs[i] == null || strs[i + 1] == null || strs[i].isEmpty()
						|| strs[i + 1].isEmpty())
					return "";
				else if (strs[i].length() == scanIndex
						|| strs[i + 1].length() == scanIndex
						|| strs[i].charAt(scanIndex) != strs[i + 1]
								.charAt(scanIndex))
					return strs[0].substring(0, scanIndex);
			}
			scanIndex++;
		}
	}

	/**
	 * 
	 */
	public LongestCommonPrefix() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
